<template>
  <div class="app-main-container">
    <QueryForm
      v-model="filters"
      :query-form-config="queryFormConfig"
      @handleQuery="getListByFilters"
      @clear="clearFilters"
    />
    <div v-if="meta.indexOf('RoleAdd') > -1" class="doumee-table-buttons">
      <el-button v-preventReClick type="primary" @click="toVipCardAdd">新增</el-button>
    </div>
    <el-table
      ref="table"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      :header-row-class-name="'table-header'"
      class="doumee-element-table"
    >
      <el-table-column align="center" label="职位ID" prop="roleId" min-width="200" fixed="left" />
      <el-table-column align="center" label="职位名称" prop="roleName" min-width="140" />
      <el-table-column align="center" label="职位说明" prop="roleSign" min-width="300" />
      <el-table-column label="操作" width="240" align="center" fixed="right">
        <template slot-scope="scope">
          <div class="flex-cc">
            <el-button v-if="meta.indexOf('RoleEdit') > -1" v-preventReClick type="text" @click="toEdit(scope.row)">编辑</el-button>
            <el-button v-if="meta.indexOf('RoleEdit') > -1" v-preventReClick type="text" @click="toBindRoleMenuList(scope.row.roleId)">分配权限</el-button>
            <el-button v-if="meta.indexOf('RoleDel') > -1" v-preventReClick type="text" style="color: red;" @click="toDelete(scope.row)">删除</el-button>
          </div>
          <!-- <span v-else>-</span> -->
        </template>
      </el-table-column>
    </el-table>

    <div class="flex-cc doumee-pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        hide-on-single-page
        @current-change="currentChange"
      />
    </div>

    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" title="新增角色" :visible.sync="showAddRole">
      <el-form ref="addForm" :rules="rules" :model="newRoleData" label-width="100px">
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model="newRoleData.roleName" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="职位说明">
          <el-input v-model="newRoleData.roleSign" placeholder="请输入职位说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddRole = false">取 消</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="comfirmAddNewRole">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog :close-on-click-modal="modalDialog" :lose-on-press-escape="modalDialog" title="编辑角色" :visible.sync="showEditRole">
      <el-form ref="editForm" :rules="rules" :model="editRoleData" label-width="100px">
        <el-form-item label="职位名称" prop="roleName">
          <el-input v-model="editRoleData.roleName" placeholder="请输入职位名称" />
        </el-form-item>
        <el-form-item label="职位说明">
          <el-input v-model="editRoleData.roleSign" placeholder="请输入职位说明" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditRole = false">取 消</el-button>
        <el-button v-preventReClick :loading="subLoading" type="primary" @click="comfirmEditRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { roleListPost, roleAddPost, roleEditPost, roleDelPost } from '@/api'
import { queryFormConfig } from './config'
export default {
  name: 'RoleList',
  data() {
    return {
      modalDialog: this.$store.state.app.dialog,
      queryFormConfig,
      subLoading: false,
      meta: [],
      buttons: {},
      list: [],
      pagination: {
        page: 1,
        rows: 10,
        firstQueryTime: new Date()
      },
      total: 0,
      marketingActiveName: 'first',
      filters: {
        name: ''
      },
      showAddRole: false,
      newRoleData: {
        name: '',
        info: ''
      },
      showEditRole: false,
      editRoleData: {},
      showBindRoleMenu: false,
      activeBindRoleMenuTab: 'firstBindRoleMenuTab',
      allRoleMenu: [],
      rules: {
        roleName: [
          { required: true, message: '请输入职位名称', trigger: 'blur' }
        ],
        info: [
          { required: true, message: '请输入职位说明', trigger: 'blur' }
        ]
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      const buttons = to.meta.buttons
      for (const i in buttons) {
        vm.buttons[buttons[i]] = true
      }
    })
  },
  created() {
    this.meta = this.$route.meta.buttons || []
    this.getRoleList()
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  activated() {
    this.$nextTick(() => {
      this.$refs.table.doLayout()
    })
  },
  methods: {
    // 获取列表
    getRoleList() {
      const { pagination, filters: param } = this
      roleListPost({ pagination, param }).then(res => {
        this.list = res.recordList
        this.total = res.totalCount
        const t = res.totalCount / 10
        const count = Number(t.toFixed(0)) + (t - t.toFixed(0) > 0 ? 1 : 0)
        this.total = count * 10
      })
    },
    getListByFilters() {
      this.pagination = {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      }
      this.getRoleList()
    },
    clearFilters() {
      this.filters = { name: '' }
      this.pagination = {
        firstQueryTime: new Date(),
        page: 1,
        rows: 10
      }
      this.getRoleList()
    },
    // 切换分页
    currentChange(page) {
      this.$set(this.pagination, 'page', page)
      this.getRoleList()
    },
    // 新增
    toVipCardAdd() {
      this.showAddRole = true
      this.newRoleData = {}
    },
    // 确认新增
    comfirmAddNewRole() {
      const that = this
      const { newRoleData } = this
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          this.subLoading = true
          roleAddPost({ param: { ...newRoleData }}).then(res => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              that.$message.success('新增成功')
              that.showAddRole = false
              that.getRoleList()
              that.newRoleData = {}
            }
          }).catch(() => {
            this.subLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 编辑
    toEdit(data) {
      this.showEditRole = true
      this.editRoleData = { ...data }
    },
    // 确认编辑
    comfirmEditRole() {
      const { editRoleData } = this
      const that = this
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.subLoading = true
          roleEditPost({ param: { ...editRoleData }}).then(res => {
            this.subLoading = false
            if (res.errorCode === '000000') {
              that.$message.success('编辑成功')
              that.showEditRole = false
              that.getRoleList()
              that.editRoleData = {}
            }
          }, () => {
            this.subLoading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      }).catch(() => {
        this.subLoading = false
      })
    },
    // 删除
    toDelete(row) {
      const that = this
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        roleDelPost({ param: { roleId: row.roleId }}).then(res => {
          that.$message.success('删除成功')
          that.getRoleList()
        })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 分配权限
    toBindRoleMenuList(id) {
      this.$router.push({ path: '/accountOptions/roleBind', query: { roleId: id }})
    }
  }
}
</script>
